package com.cg.asm.body.service.user.impl;

import com.cg.asm.body.dao.user.UserMapper;
import com.cg.asm.body.domain.dto.user.UserInfoDTO;
import com.cg.asm.body.domain.dto.user.UserRoleDTO;
import com.cg.asm.body.domain.vo.user.UserEditVO;
import com.cg.asm.body.domain.vo.user.UserPagedVO;
import com.cg.asm.body.domain.vo.user.UserRoleVO;
import com.cg.asm.body.service.user.IUserInfoService;
import com.cg.asm.body.util.AsmBodyCommonUtil;
import com.cg.asm.client.AsmUUID;
import com.cg.asm.client.domain.menu.MenuUrlLoginVO;
import com.cg.asm.client.domain.user.UserInfo;
import com.cg.asm.client.exception.AsmException;
import com.cg.asm.client.exception.MybatisExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@EnableTransactionManagement(proxyTargetClass = true)
public class UserInfoService implements IUserInfoService {

    @Resource
    private UserMapper userMapper;

    /**
     * 查询用户信息
     *
     * @param mybatisExample
     * @return
     */
    public PageInfo<UserPagedVO> selectByUserInfo(MybatisExample mybatisExample) {
        PageHelper.startPage(mybatisExample.getOffset(), mybatisExample.getLimit());
        UserInfo userLoginVO = AsmBodyCommonUtil.getCurrentUserLoginVO();
        String userId = userLoginVO.getUserId();
        Map<String, String> param = new HashMap<>();
        param.put("selfUserId", userId);
        if (!"super".equals(userId)) {
            List<MenuUrlLoginVO> userPoints = userLoginVO.getUserPoints();
            // CXSYYH:表示查询所有用户
            if (!AsmBodyCommonUtil.permission(userPoints, "CXSYYH")) {
                //如果不是超级管理员（super）并且非CXSYYH，则只查询自己创建的用户
                param.put("creatorUserId", userId);
            }
        }
        mybatisExample.setParameter(AsmBodyCommonUtil.mybatisExampleMergeParam(mybatisExample, param));
        List<UserPagedVO> users = userMapper.selectByUserInfo(mybatisExample);
        return new PageInfo<>(users);
    }

    /**
     * 验证用户唯一性
     *
     * @param username
     * @return
     */
    public boolean userIsUnique(String username) {
        if (StringUtil.isNotEmpty(username)) {
            String resultName = userMapper.userIsUnique(username);
            if (StringUtil.isNotEmpty(resultName)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 增加用户信息
     *
     * @param userInfoDTO
     */
    @Override
    public void saveUser(UserInfoDTO userInfoDTO) {
        if (null != userInfoDTO && StringUtil.isNotEmpty(userInfoDTO.getUsername())) {
            userInfoDTO.setUserId(AsmUUID.generate());
            userInfoDTO.setCreatorUserId(AsmBodyCommonUtil.getCurrentUserLoginVO().getUserId());
            userInfoDTO.setCreatorDate(new Date());
            userInfoDTO.setErrorLoginNumber("0");
            String password = userInfoDTO.getPassword();
            if (StringUtil.isNotEmpty(password)) {
                String encoderPwd = AsmUUID.pwdEnCoder(AsmBodyCommonUtil.getRequest(), password);
                if (StringUtil.isNotEmpty(encoderPwd)) {
                    userInfoDTO.setPassword(encoderPwd);
                } else {
                    throw new AsmException("保存用户信息失败，密码加密失败!");
                }
            } else {
                throw new AsmException("保存用户信息失败，用户密码不能为空!");
            }
            userMapper.saveUser(userInfoDTO);
        } else {
            throw new AsmException("保存用户信息失败，未获取用户信息，或用户名称为空！");
        }
    }

    /**
     * 根据用户Id，查询编辑用户的详细信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserEditVO userEditInfo(String userId) {
        return userMapper.userEditInfo(userId);
    }

    /**
     * 保存编辑的用户信息
     *
     * @param userInfoDTO
     */
    @Override
    public void saveEditUser(UserInfoDTO userInfoDTO) {
        if (null != userInfoDTO && StringUtil.isNotEmpty(userInfoDTO.getUserId())) {
            userMapper.saveEditUser(userInfoDTO);
        } else {
            throw new AsmException("更新用户信息失败，用户名称为空！");
        }
    }

    /**
     * 根据用户Id删除用户信息
     *
     * @param ids
     */
    @Override
    public void delUser(String[] ids) {
        if (null != ids && ids.length != 0) {
            userMapper.delUser(ids);
            for (String id : ids) {
                userMapper.delUserRole(id);
            }
        } else {
            throw new AsmException("删除失败，用户Id不能为空!");
        }
    }

    /**
     * 根据用户Id更新用户状态
     *
     * @param ids
     * @param status
     */
    @Override
    public void updateStatus(String[] ids, String status) {
        if (null != ids && ids.length != 0) {
            if ("start".equals(status)) {
                userMapper.startAccountStatus(ids);
            } else if ("stop".equals(status)) {
                userMapper.stopAccountStatus(ids);
            }
        } else {
            throw new AsmException("状态更新失败，用户Id不能为空!");
        }
    }

    /**
     * 根据用户Id重置密码
     *
     * @param userId
     */
    @Override
    public void resetPwd(String userId) {
        if (StringUtil.isNotEmpty(userId)) {
            String newPwd = AsmUUID.pwdEnCoder(AsmBodyCommonUtil.getRequest(), "11111111");
            if (StringUtil.isNotEmpty(newPwd)) {
                userMapper.updateUserPwd(newPwd, userId);
            } else {
                throw new AsmException("密码重置失败，密码加密失败!");
            }
        } else {
            throw new AsmException("密码重置失败，用户Id不能为空!");
        }
    }

    /**
     * 保存选择的角色
     *
     * @param userRoleVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserRole(UserRoleVO userRoleVO) {
        if (null != userRoleVO && StringUtil.isNotEmpty(userRoleVO.getUserId())) {
            userMapper.delUserRole(userRoleVO.getUserId());
            if (null != userRoleVO.getRoleIds()) {
                for (String roleId : userRoleVO.getRoleIds()) {
                    UserRoleDTO userRoleDTO = new UserRoleDTO();
                    userRoleDTO.setUserRoleCode(AsmUUID.generate());
                    userRoleDTO.setUserId(userRoleVO.getUserId());
                    userRoleDTO.setRoleId(roleId);
                    userMapper.saveUserRole(userRoleDTO);
                }
            }
        } else {
            throw new AsmException("分配角色失败：缺失用户Id信息");
        }
    }

    @Override
    public List<String> roleByUser(String userId) {
        return userMapper.roleByUser(userId);
    }

    @Override
    public void saveUpAvatar(String upAvatar, String userId) {
        if (StringUtils.isNotEmpty(upAvatar) && StringUtils.isNotEmpty(userId)) {
            userMapper.saveUpAvatar(upAvatar, userId);
        } else {
            throw new AsmException("上传头像失败：缺失图像或用户信息");
        }

    }
}
